<template>
  <div>
    <el-tooltip
      v-if="overtxt"
      class="item"
      effect="dark"
      :content="text"
      placement="top-start"
    >
      <div class="pointer">{{ showAncestorsName }}</div>
    </el-tooltip>
    <div v-else>{{ showAncestorsName }}</div>
  </div>
</template>

<script>
export default {
  components: {},
  props: {
    text: [String, Number],
    maxLength: [String, Number],
  },
  data() {
    return {
      showAncestorsName: "",
      overtxt: false,
    };
  },
  watch: {
    text: {
      immediate: true,
      handler(e) {
        this.overtxt = (e?e.length:0 )> this.maxLength;
        this.showAncestorsName = this.truncateFieldsSmartly(e, this.maxLength);
      },
    },
  },
  methods: {
    truncateFieldsSmartly(t, max) {
      if (t && t.length > max) {
        let arr = t.split("/");
        // 如果只有一个目录
        if (arr.length == 1) {
          return arr[0].length > max ? arr[0].substring(0, max - 1) + "..." : arr[0];
        }
        // 非一个目录
        else {
          let finishT = arr[arr.length - 1];
          // 如果最后一个过长则 保留第一个
          if (finishT.length > max - 1 - 3) {
            return arr[0].substring(0, max - 1) + "...";
          } else {
            // 获取最后一个 / 之前的所有字符
            const lastSlashIndex = t.lastIndexOf("/");
            let startT = t.substring(0, lastSlashIndex);
            // 前面字符 保留 50-最后的长度
            return `${startT.substring(
              0,
              max - 1 - finishT.length - 3
            )}.../${finishT}`;
          }
        }
      } else {
        return t;
      }
    },
  },
  created() {},
  mounted() {},
};
</script>
<style scoped lang='scss'>
</style>
